package com.kabuda.zhugehot200;

import java.util.HashSet;

/**
 * @author kabuda
 * @date 2025-03-15 14:37
 * @description 统计n以内的素数的个数
 */
public class t204_素数个数统计 {


    public static void main(String[] args) {
        System.out.println(bf(499979));
        System.out.println(eratosthenes(499979));
    }

    /**
     * 埃筛法
     *
     * @param n
     * @return
     */
    public static int eratosthenes(int n) {
        int count = 0;
        //false代表素数
        boolean[] isPrime = new boolean[n];
        for (int i = 2; i < n; i++) {
            if (!isPrime[i]) {
                count++;
                if ((long) i * i < n) { //避免超出int范围变成负数
                    //质数*质数=合数
                    //合数+质数=合数
                    for (int j = i * i; j < n ; j += i) {
                        isPrime[j] = true;
                    }
                }

            }
        }
        return count;
    }


    /**
     * 暴力破解法
     *
     * @param n
     * @return
     */
    public static int bf(int n) {
        HashSet set = new HashSet();

        int count = 0;
        for (int i = 2; i < n; i++) {
            boolean flag = true;
            for (int j = 2; j <= Math.sqrt(i); j++) {
                if (i % j == 0) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                set.add(i);
                count++;
            }
        }
        return count;
    }
}
